<template>
  <Modal
    v-model:visible="visible"
    :title="title"
    :confirm-loading="confirmLoading"
    @ok="handlerSubmit"
    cancelText="取消"
    okText="确认"
  >
    <template v-if="loading">
      <div class="empty-tips">测试中...</div>
    </template>
    <template v-if="!loading">
      <Result :status="result?.status" :title="result?.title"></Result>
    </template>
  </Modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { Result } from 'ant-design-vue';
import { Modal } from 'ant-design-vue';
import { testDataSource } from '/@/api/system-mgmt/source-mgmt/source';

const visible = ref<boolean>(false);
const emit = defineEmits(['success', 'register']);
const title = ref('数据源测试');
const loading = ref(true);
const confirmLoading = ref<boolean>(false);

const result = ref();

var res;
const param = ref();

const closeModal = () => {
  visible.value = false;
};

const showModal = async (record: Recordable) => {
  visible.value = true;
  result.value = {};
  param.value = record.id;

  loading.value = true;
  confirmLoading.value = true;

  try {
    res = await testDataSource({ rdsId: param.value });
    if (res === '数据源信息连接成功') {
      loading.value = false;
      result.value = {
        status: 'success',
        title: '测试数据源连接成功',
      };
    } else {
      loading.value = false;
      result.value = {
        status: 'error',
        title: '测试数据源连接失败',
      };
    }
    loading.value = false;
    confirmLoading.value = false;
  } catch (e) {
    loading.value = false;
    result.value = {
      status: 'error',
      title: '测试数据源连接失败',
    };
    loading.value = false;
    confirmLoading.value = false;
  }
};

async function handlerSubmit() {
  closeModal();
  emit('success');
}

defineExpose({ showModal });
</script>

<style scoped>
.empty-tips {
  height: 100px;
  line-height: 100px;
  text-align: center;
}
</style>
